﻿using System;
using System.Linq;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

namespace TfsWrapper.Commands
{
    public class GetByIdCommand : TfsCommand
    {
        private readonly IOutputPrinter<IssueData> printer;

        public GetByIdCommand(IOutputPrinter<IssueData> printer)
        {
            this.printer = printer;
        }

        public override void Execute(TfsConnection tfs, params string[] args)
        {
            var id = ValidateArgs(args);

            var wis = tfs.GetService<WorkItemStore>();

            var workItem = wis.GetWorkItem(id);

            printer.Print(new IssueData
                              {
                                  Id = workItem.Id.ToString(),
                                  Summary = workItem.Title,
                                  Url = MakeWorkItemUrl(tfs, workItem),
                                  State = workItem.State,
                                  Resolved = IsResolved(workItem)
                              });
        }

        private int ValidateArgs(string[] args)
        {
            if (args.Length != 1)
                throw new InvalidOperationException(
                    string.Format("Command {0} expects one argument but {1} were supplied{2}.",
                                  GetType().Name,
                                  args.Length > 0 ? args.Length.ToString() : "none",
                                  args.Length > 0 ? ": " + string.Join(", ", args) : ""));

            int id;

            if (int.TryParse(args[0], out id) == false)
                throw new FormatException(
                    string.Format("Command {0} expects an integer argument. {1} cannot be parsed to an integer.",
                                  GetType().Name, args[0]));

            return id;
        }

        private static bool IsResolved(WorkItem workItem)
        {
            return new[] {"resolved", "closed"}.Any(s => s.Equals(workItem.State, StringComparison.OrdinalIgnoreCase));
        }
    }
}